package org.testis.communication.client;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;

/**
 * A class to create a client over TCP.
 * @author nurhat
 */
public class AtofTcpClient {

    private Socket clientSocket;
    private int m_keepAliveTime;
    private int m_portNumber;
    private String m_ipAddress;
    private String m_stringToSend;
    private DataInputStream m_in;
    private DataOutputStream m_out;
    private StringBuilder m_lastError;

    /**
     * Creates telnet client
     * @param keepAliveTime
     * @param portNumber
     * @param ipAddress
     * @param stringToSend
     */
    public AtofTcpClient(int keepAliveTime,
            int portNumber,
            String ipAddress,
            String stringToSend) {
        m_keepAliveTime = keepAliveTime;
        m_portNumber = portNumber;
        m_ipAddress = ipAddress;
        m_stringToSend = stringToSend;
        m_lastError = new StringBuilder();
    }

    /**
     * Binds to server over given parameters.
     * Send a message to server and wait for the server result
     * @return answer of server
     * @throws java.io.IOException
     */
    public String waitForServerMessage() {
        String output = null;
        try {
            clientSocket = new Socket();
            clientSocket.setSoTimeout(m_keepAliveTime);
            SocketAddress address = new InetSocketAddress(m_ipAddress,
                    m_portNumber);
            clientSocket.connect(address);


            m_in = new DataInputStream(clientSocket.getInputStream());
            m_out = new DataOutputStream(clientSocket.getOutputStream());

            m_out.writeUTF(m_stringToSend);
            output = m_in.readUTF();

        }  catch (ConnectException ex) {
            m_lastError.append("No server found on given ip port[" + m_ipAddress + "," + m_portNumber + "]. Client couldnt connected to server");
        }catch (Exception ex) {
            m_lastError.append(ex.toString());
        } finally {
            try {
                if (clientSocket != null) {
                    clientSocket.close();
                }
                if (m_in != null) {
                    m_in.close();
                }
                if (m_out != null) {
                    m_out.close();
                }
            } catch (IOException ex) {
            } catch (Exception ex) {
            }
        }
        return output;
    }
      /**
     * @return the m_lastError
     */
    public String getLastError() {
        return m_lastError.toString();
    }
}
